﻿namespace GoodAdmin.CodeGenerator;

public class CodeGenService : DbRepository<CodeGenData>, ICodeGenService, ITransient
{
    /// <inheritdoc/>
    public async Task<SqlSugarPagedList<CodeGenData>> GetBaseList(CodeGenDataPageInput input)
    {
        return await Context.Queryable<CodeGenData>()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Category), it => it.Category == input.Category)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), it => it.Name.Contains(input.Name))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Type), it => it.Type == input.Type)
            .OrderByIF(!string.IsNullOrWhiteSpace(input.SortField), o => $"{input.SortField} {input.SortOrder}")
            .ToPagedListAsync(input.PageIndex, input.PageSize);
    }

    /// <inheritdoc/>
    public async Task<CodeGenData> GetDetail(long id) {
        var data = await GetByIdAsync(id);
        if (data == null)
        {
            throw Oops.Bah(CodeGenErrorCode.CG005);
        }
        return data;
    }

    /// <inheritdoc/>
    public async Task Add(CodeGenDataAddInput input)
    {
        await CheckInput(input);

    }
    /// <inheritdoc/>
    public Task Delete(BaseIdInput input)
    {
        throw new NotImplementedException();
    }
    /// <inheritdoc/>
    public Task Update(CodeGenDataUpdateInput input)
    {
        throw new NotImplementedException();
    }
    /// <inheritdoc/>
    public Task CodeDownload()
    {
        throw new NotImplementedException();
    }
    /// <inheritdoc/>
    public Task CodePriview()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 创建数据表
    /// </summary>
    //private static void CreateTable(string code,List<CodeGenDetailData> tableInfo)
    //{
    //    //判断是否有设置数据表名
    //    tableInfo.ForEach(it => {
    //        //如果表名为空
    //        if (string.IsNullOrWhiteSpace(it.TableName))
    //        {
    //            var tableType = it.TableType == CodeGenConst.TableType_Main ? it.TableType : it.TableType + YitIdHelper.NextId();
    //            it.TableName = $"{code}_{tableType}";
    //        }
    //    });
    //}
    //private static void UpdateTable()
    //{

    //}

    public async Task CheckInput(CodeGenDataAddInput baseInfo)
    {
        var baseInfoList = await GetListAsync();
        if (baseInfoList.Any(it => it.Name == baseInfo.Name))
        {
            throw Oops.Bah(CodeGenErrorCode.CG001);
        }
        if (baseInfoList.Any(it => it.Code == baseInfo.Code))
        {
            throw Oops.Bah(CodeGenErrorCode.CG002);
        }
    }
}